<template>
  <div class='container'>
    <div class="app-container">
      <!-- 卡片 -->
      <el-card shadow="never">
        <div slot="header" class="clearfix">
          <span v-if="formData.id">修改试题</span>
          <span v-else>试题录入</span>
        </div>
        <!-- 表单 -->
        <el-form :model="formData" ref="formData" :rules="rules" :label-position="labelPosition" label-width="100px">
    <!-- 下拉菜单 Select 选择器-->
        <!-- 学科 -->
          <el-form-item label="学科：" prop="subjectID">
            <el-select  v-model="formData.subjectID" placeholder="请选择" style="width: 450px;">
              <el-option v-for="item in discipline"
              :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item label="目录：" prop="catalogID">
            <el-select v-model="formData.catalogID" placeholder="请选择" style="width: 450px;">
              <el-option
                v-for="item in directory"
                :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select v-model="formData.enterpriseID" placeholder="请选择" style="width: 450px;">
              <el-option :label="item.company" v-for="item in enterprise" :key="item.id" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
            <el-form-item label="城市：" prop="province" style="display:inline-block;">
            <el-select
              class="filter-item"
              style="width: 220px;"
              v-model="formData.province"
              @keyup.enter="handleFilter"
              @change="handleProvince"
              filterable
            >
              <el-option
                v-for="(item,idx) in Provinces"
                :key="idx"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            </el-form-item >
            <el-form-item style="display:inline-block;" prop="city" label-width="0">
            <el-select
              class="filter-item"
              style="width: 220px;margin-left:10px"
              v-model="formData.city"
              @keyup.enter="handleFilter"
              filterable
            >
              <el-option
                v-for="(item,idx) in citys"
                :key="idx"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 方向 -->
           <el-form-item label="方向：" prop="direction">
            <el-select v-model="formData.direction" placeholder="请选择" style="width: 450px;">
              <el-option :label="item" v-for="(item,idx) in directions" :key="idx" :value="item"></el-option>
            </el-select>
          </el-form-item>
    <!-- 单选 -->
        <!--题型  -->
          <el-form-item label="题型:">
          <el-radio-group v-model="formData.questionType">
            <el-radio :label="item.value.toString()"
             v-for="item in questionType"
             :key="item.value"
            >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
    <!-- 单选 -->
          <el-form-item label="难度:">
          <el-radio-group v-model="formData.difficulty">
            <el-radio :label="item.value.toString()"
              v-for="item in difficulty"
              :key="item.value"
            >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
    <!-- 富文本 -->
          <el-form-item label="题干：" prop="titleStem">
            <quill-editor v-model="formData.question" :options="editorOption" ></quill-editor>
          </el-form-item>
    <!-- 输入框 上传图片 -->
    <!--  选项 单选-->
         <el-form-item label="选项：" v-if="formData.questionType === '1'" v-model='formData.options'>
             <div v-for="(item, index) in formData.options" :key="index" style="margin-bottom:30px" @click="imgID = index">
                <el-radio v-model="formData.radioContent" :label="item.code" @change="radioChange(item)" style="margin-right:0">
                  <span>{{item.code}}：</span>
                </el-radio>
                <input style="width: 270px;height:40px" v-model="item.title">
                <div class="file">
                    <input type="file" class="updata"  accept="image/*" @change="change($event)" ref="updata">
                    <img :src="item.img ? item.img : baseImg" alt="" class="img" >
                    <span v-show="!item.img">上传图片</span>
                    <i class="el-icon-circle-close el-span"></i>
                </div>
             </div>
              <br>
            <el-button type="danger" :disabled='disabled' @click="addRadio">+增加选项与答案</el-button>
          </el-form-item>
          <!-- 多选 -->
         <el-form-item label="选项：" v-else-if="formData.questionType === '2'">
          <div v-for="(item, index) in formData.options" :key="item.index" style="margin-bottom:30px" @click="imgID = index">
              <el-checkbox type='checkbox' :label='item.code' v-model="item.isRight" >
                <span>{{item.code}}：</span>
              </el-checkbox>
             <input style="width: 270px;height:40px" v-model="item.title">
                <div class="file">
                    <input type="file" class="updata"  accept="image/*" @changeImg="change($event)" ref="updata">
                    <img :src="item.img ? item.img : baseImg" alt="" class="img">
                    <span v-if="!item.img">上传图片</span>
                    <i class="el-icon-circle-close el-span"></i>
                </div>
          </div>
            <el-button type="danger" :disabled='!disabled' @click="addRadio">+增加选项与答案</el-button>
          </el-form-item>

    <!-- 输入框 -->
          <el-form-item label="解析视频：" prop="name" style="margin-top:10px" v-model="formData.videoURL">
            <el-input v-model="formData.videoURL" style="width: 450px;"></el-input>
          </el-form-item>
    <!-- 富文本 -->
          <el-form-item label="答案解析：" prop="answerAnalysis">
            <quill-editor v-model="formData.answer" :options="editorOption"></quill-editor>
          </el-form-item>
    <!-- 简介 -->
          <el-form-item label="题目备注：" prop="desc">
            <el-input type="textarea" v-model="formData.remarks" style="width: 450px;"></el-input>
          </el-form-item>
    <!-- 简介下拉菜单 -->
          <el-form-item label="试题标签：">
            <el-select v-model="formData.tags" placeholder="请选择"  style="width: 370px;">
              <el-option :label="item.label" v-for="item in tagsS"  :key="item.value" :value="item.label" ></el-option>
            </el-select>
          </el-form-item>
    <!-- 提交按钮 -->
          <el-form-item>
            <el-button v-if="formData.id" type="success" v-loading="loading" @click="modifyForm()">修改提交</el-button>
            <el-button v-else type="primary" :loading="loading" @click="submitForm()">确定提交</el-button>

          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// 导入样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// 导入组件
import { quillEditor } from 'vue-quill-editor'

// 引入接口
import { provinces, citys } from '@/api/hmmm/citys.js'
import { add, update, detail as quesDetail, directoryList } from '@/api/hmmm/questions.js'
import { simple } from '@/api/hmmm/subjects.js'
import { list } from '@/api/hmmm/companys.js'
import { simple as tagsS } from '@/api/hmmm/tags.js'
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
import { simple as catalogSimple } from '@/api/hmmm/directorys'
// 引图片
// import defaultImg from '@/assets/upImg.png'

export default {
  name: 'QuestionsNew',
  components: {
    quillEditor
  },
  data () {
    return {
      // 加载
      loading: false,
      // 方向
      direction: [],
      // 按钮隐藏和显示
      disabled: true,
      // 默认的图片
      baseImg: '',
      // 对齐方式
      labelPosition: 'right',
      // 难度
      resource: '1',
      // 城市
      citySelect: {
        province: '',
        city: ''
      },
      // 富文本
      editorOption: {
      // 占位配置
        placeholder: '',
        modules: {
        // 配置工具栏
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote', 'code-block'],
            ['image', 'link']
          ]
        }
      },
      // 学科
      discipline: [],
      // 目录
      directory: [],
      // 企业
      enterprise: [],
      // 城市
      Provinces: [],
      citys: [],
      // 试题标签
      tagsS: [],
      directions: [], // 方向
      selecDirectory: [], // 联动学科目录数据
      // 保存图片的id
      imgID: '',
      value: [],
      // selecTags: [],
      // 表单数据
      formData: {
        id: '',
        // 选项
        options: [
          {
            code: 'A',
            title: '',
            img: '', // 上传图片
            isRight: 0
          },
          {
            code: 'B',
            title: '',
            img: '', // 上传图片
            isRight: 0
          },
          {
            code: 'C',
            title: '',
            img: '', // 上传图片
            isRight: 0
          },
          {
            code: 'D',
            title: '',
            img: '', // 上传图片
            isRight: 0
          }
        ],
        // 单选
        radioContent: '',
        checkList: [],
        // 视频
        videoURL: '',
        direction: '', // 方向
        answer: '', // 答案解析
        remarks: '', // 题目备注
        question: '', // 题干
        difficulty: '1', // 难度
        questionType: '1', // 题型
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 省
        city: '', // 城市 市
        tags: ''
      },
      requestParameters: {
        subjectName: ''
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        titleStem: [
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择市', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择市', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ]
      // answerAnalysis: [
      //     { required: true, message: '请填写答案解析', trigger: 'change' }
      //   ]
      }
    }
  },
  created () {
    this.getDiscipline()
    this.getEnterprise()
    this.getProvinces()
    this.getdirection()
    // 获取默认显示的图片
    this.baseImg = require('@/assets/upImg.png')
    // 页面跳转
    this.receiveForm()
  },
  // 监听学科
  watch: {
    'formData.subjectID' (id) {
      this.getDirectory(id)
      this.getTags()
    }
  },
  methods: {
    change (e) {
    // 判断是不是规定格式
    // let name  =  e.target.files[0].name
    // 获取到第一张图片
      const file = e.target.files[0]
      // 创建文件读取对象
      var reader = new FileReader()
      //  将文件读取为DataURL
      reader.readAsDataURL(file)
      // 读取成功调用方法
      reader.onload = e => {
      // e.target.result 获取 读取成功后的  文件DataURL
        this.formData.options[this.imgID].img = e.target.result
      // 如果要将图片上传服务器，就在这里调用后台方法
      }
    },
    // 接收表单的数据
    async receiveForm () {
      if (this.$route.query.id) {
        const { data: res } = await quesDetail({
          id: this.$route.query.id
        })
        this.formData = res
        console.log('111', res)
        // 获取目录列表
        const res1 = await directoryList(res.subjectID)
        console.log('222', res1)
        // this.directoryName = res.directoryName
        // console.log('3333', res)
        // this.value = res.tags.split(',')
        this.formData.id = parseInt(this.$route.query.id)
        this.formData.options = res.options.map(item => {
          delete item.multiple
          item.isRight = !!item.isRight
          return item
        })
        this.formData.addDate = new Date()
        if (res.questionType === '1') {
          this.formData.options.forEach(item => {
            if (item.isRight === true) {
              this.radio = item.code
            }
          })
        }
        this.formData.creatorID = '2'
        this.directory.forEach(val => {
          if (val.subjectName === this.requestParameters.subjectName) {
            this.directory.push({
              id: val.id,
              name: val.directoryName
            })
          }
        })
        // this.tagsS.forEach(value => {
        //   if (value.subjectName === this.name) {
        //     this.formData.tags.push(value.tagName)
        //   }
        // })
      }
    },
    // 方向
    getdirection () {
      this.directions = direction
    },
    // 添加单选图片
    addRadio () {
      this.formData.options.push({
        code: String.fromCharCode(65 + this.formData.options.length),
        img: '',
        title: '',
        isRight: ''
      })
    },
    radioChange (val) {
      this.formData.options.forEach(item => {
        if (val === item) {
          item.isRight = 1
        } else {
          item.isRight = 0
        }
      })
    },
    // 标签
    async getTags () {
      const { data: res } = await tagsS({ tagName: '' })
      this.tagsS = res
    },
    // 学科事件监听
    // hChangeDiscipline (id) {
    //   console.log(id)
    // },
    // 城市下拉框变化
    handleProvince (e) {
      this.getCitys(e)
    },
    // 城市
    getProvinces () {
      this.Provinces = provinces()
    },
    getCitys (e) {
      this.citys = citys(e)
      this.formData.city = this.citys[0]
    },
    // 企业
    async getEnterprise () {
      const { data: res } = await list({ shortName: '' })
      this.enterprise = res.items
    },
    // 目录获取
    async getDirectory (data) {
      const res = await catalogSimple({ subjectID: this.formData.subjectID })
      this.directory = res.data
      // this.formData.catalogID.toString()
    },
    // 学科获取数据
    async getDiscipline () {
      // try {
      //   const res = await simple()
      //   this.discipline = res.data
      // } catch (error) {
      // }
      const res = await simple()
      this.discipline = res.data
      // this.formData.subjectID = '' + this.formData.subjectID
    },
    // 表单确认
    submitForm () {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          try {
            console.log(typeof this.formData.tags)
            this.loading = true
            this.sendForm()
          } catch (error) {
            console.log(error)
            this.loading = true
            this.$message.error('录入失败失败')
          }
        } else {
          return false
        }
      })
    },
    async sendForm () {
      const data = {
        ...this.formData
      }
      try {
        await add(data)
        this.$router.push('/questions/list')
        this.$message.success('录入成功')
      } catch (err) {
        console.log(err)
      }
    },
    // 确定修改
    modifyForm (formData) {
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          try {
            await update(this.formData)
            // this.discipline.forEach(item => {
            //   this.tagsS.forEach(value => {
            //     if (value.subjectName === item.subjectName) {
            //       this.selecTags.push(value.tagName)
            //     }
            //   })
            // })
            this.$message.success('修改成功')
            this.$router.push('/questions/list')
            this.resetForm()
            // console.log(res)
          } catch (error) {
            console.log(error)
            this.$message.error('修改失败')
          }
        } else {
          return false
        }
      })
    },
    // 表单重置
    resetForm (formName) {
      this.$refs.formData.resetFields()
    }
  },
  computed: {
    questionType () {
      return questionType
    },
    difficulty () {
      return difficulty
    }
  }
}
</script>

<style scoped >
 /* 富文本 */
.container /deep/ .ql-editor{
  height: 300px;
}
input {
  border: 1px solid #ccc;
  outline: none;

}

.file {
  vertical-align:middle;
  margin-left: 10px;
  display: inline-block;
  text-align: center;
  /* overflow: hidden; */
  line-height: 72px;
  position: relative;
  width: 102px;
  height: 62px;
  border: 1px dashed #ccc;
  border-radius: 5px;
  }
  .updata {
    display: block;
    height: 100%;
    width: 100%;
    opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 10;
  }
  .img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100px;
    height: 60px;
  }
  .file span{
    position: absolute;
    left: 25%;
    top: -10%;
  }
.el-span{
  position: absolute;
  font-size: 20px;
  right: -10px;
  top: -10px;
}
 .file:hover{
   border-color: #6fb6ff;
 }
</style>
